<template>
  <view class="login-container">
     <uni-icons type="contact-filled" size="100" color="AFAFAF"></uni-icons>
     
     <button type="primary" class="btn-login"  @click="getUserInfo">一键登录</button>
     
     <view class="tips-text">
        登录后享更多实惠
     </view>
  </view>
</template>
<script>
  import {mapMutations,mapState} from 'vuex'
  export default{
    data(){
      return{
        
      }
    },
    computed:{
      ...mapState({
        redirectInfo:state=>state.user.redirectInfo
      })
    },
    methods:{
      //用户授权之后,获取用户基本信息
      getUserInfo(){
       uni.getUserProfile({
       					desc: "获取你的昵称、头像、地区及性别",
       					success: (e) => {
                    this.$store.commit('UpdateUserInfo',e.userInfo)
                    this.getToken(e)
       					},
       					fail() {
       						uni.$showMsg('您取消了授权')
       					}
                
       				})
      },
     async getToken(info){
        //获取对应code值
      const [err,res] = await uni.login().catch(err => err)
      console.log(res);
      
      if(err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败!')
      
      // 准备参数
      const query = {
        code:res.code,
        encryptedData: info.encryptedData,
            iv: info.iv,
            rawData: info.rawData,
            signature: info.signature
      }
       // 换取 token
        const { data: loginResult } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
        if (loginResult.meta.status !== 400) return uni.$showMsg('登录失败！')
        console.log(loginResult);
        uni.$showMsg('登录成功')
       
        this.$store.commit('UpdateToken',res.code)
        this.navgateback()
      },
      navgateback(){
        if(this.redirectInfo && this.redirectInfo.openType==='switchTab'){
           uni.switchTab({
             url:this.redirectInfo.from,
             complete:()=> {
               this.$store.commit('UpdateRedirectInfo',null)
             }
           })
        }
      }
    }
  }
</script>
<style lang="scss">
  .login-container{
    height: 750rpx;
    display: flex;
    position: relative;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    
    &::after{
      content: '';
      display: block;
      width: 100%;
      height: 40px;
      background-color: pink;
      border-radius: 50%;
      position: absolute;
      bottom: 0;
      left: 0;
      transform:translateY(50%);
      background-color: #fff;
    }
    
    .btn-login{
      width: 80%;
      border-radius: 100px;
      margin: 15px 0;
      background-color: #c00000;
    }
    .tips-text{
       font-size: 12px;
       color: gray;
    }
  }
</style>
